package com.bbzn.user.client.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;
import com.bbzn.user.client.config.OSSProperties;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @Author: 曾俞钧
 * @Date: 2021/3/18 17:20 （日期和时间）
 */
@Slf4j
public class OSSUtil {

    /**
     * log日志
     */

    public static String[] picString = new String[]{"jpeg", "jpg", "png"};

    private String endpoint = OSSProperties.ALIYUN_ENDPOINT;
    private String accessKeyId = OSSProperties.ALIYUN_ACCESS_ID;
    private String accessKeySecret = OSSProperties.ALIYUN_ACCESS_KEY;
    private String bucketName = OSSProperties.ALIYUN_BUCKET;
    private String FOLDER = OSSProperties.ALIYUN_DIR;

    /**
     * 上传图片
     *
     * @param url
     * @throws
     */
    public void uploadImg2Oss(String url) throws IOException {
        File fileOnServer = new File(url);
        FileInputStream fin;
        try {
            fin = new FileInputStream(fileOnServer);
            String[] split = url.split("/");
            this.uploadFile2OSS(fin, split[split.length - 1]);
        } catch (FileNotFoundException e) {
            throw new IOException("图片上传失败");
        }
    }

    //上传图片
    public String uploadImg(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        Random random = new Random();
        String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
        try {
            BufferedImage image = toBufferedImage(file);//修改图片大小

            BufferedImage bufferedImage = Thumbnails.of(image).size(700, 467).asBufferedImage();//修改图片大小
            /*   BufferedImage bufferedImage= Thumbnails.of(file.getInputStream()).size(700, 467).outputQuality(1).asBufferedImage();*/
            if (substring.equals(".png")) {
                this.uploadFile2OSS(bufferedImagePNRToInputStream(bufferedImage), name);//修改图片大小
            } else {
                this.uploadFile2OSS(bufferedImageToInputStream(bufferedImage), name);//修改图片大小
            }
            return name;
        } catch (Exception e) {
            throw new IOException("图片上传失败");
        }
    }


    //上传视频
    public String uploadVideo(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        String prestring = originalFilename.substring(0, originalFilename.lastIndexOf("."));
        Random random = new Random();
        String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
        try {
            InputStream stream = file.getInputStream();
            String filename = System.currentTimeMillis() + prestring + substring;
            OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            PutObjectResult result = client.putObject(bucketName, "Video/" + filename, stream);
            client.shutdown();
            return "Video/" + filename;
        } catch (Exception e) {
            throw new IOException("视频上传失败");
        }
    }

    //上传excel
    public String uploadExcel(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
//        String prestring = originalFilename.substring(0, originalFilename.lastIndexOf("."));
        Random random = new Random();
        String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
        try {
            InputStream stream = file.getInputStream();
            String filename = System.currentTimeMillis() + "-excel" + substring;
            OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            PutObjectResult result = client.putObject(bucketName, "excel/" + filename, stream);
            client.shutdown();
            return "excel/" + filename;
        } catch (Exception e) {
            throw new IOException("excel上传失败");
        }
    }

    /**
     * 获得图片路径
     *
     * @param fileUrl
     * @return
     */
    public String getImgUrl(String fileUrl) {
        if (!StringUtils.isEmpty(fileUrl)) {
            String[] split = fileUrl.split("/");
            if (split[0].equals("Video")) {
                return this.getUrl("Video/" + split[split.length - 1]);
            }
            return this.getUrl(this.FOLDER + split[split.length - 1]);
        }
        return "";
    }

    /**
     * 上传到OSS服务器 如果同名文件会覆盖服务器上的
     *
     * @param instream 文件流
     * @param fileName 文件名称 包括后缀名
     * @return 出错返回"" ,唯一MD5数字签名
     */
    public String uploadFile2OSS(InputStream instream, String fileName) {
        String ret = "";
        try {
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            // 创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(instream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            // 上传文件
            PutObjectResult putResult = ossClient.putObject(bucketName, FOLDER + fileName, instream, objectMetadata);
            ret = putResult.getETag();

        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                if (instream != null) {
                    instream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }

    /**
     * Description: 判断OSS服务文件上传时文件的contentType
     */
    public static String getcontentType(String filenameExtension) {
        if (filenameExtension.equalsIgnoreCase("bmp")) {
            return "image/bmp";
        }
        if (filenameExtension.equalsIgnoreCase("gif")) {
            return "image/gif";
        }
        if (filenameExtension.equalsIgnoreCase("jpeg") || filenameExtension.equalsIgnoreCase("jpg")
                || filenameExtension.equalsIgnoreCase("png")) {
            return "image/jpeg";
        }
        if (filenameExtension.equalsIgnoreCase("html")) {
            return "text/html";
        }
        if (filenameExtension.equalsIgnoreCase("txt")) {
            return "text/plain";
        }
        if (filenameExtension.equalsIgnoreCase("vsd")) {
            return "application/vnd.visio";
        }
        if (filenameExtension.equalsIgnoreCase("pptx") || filenameExtension.equalsIgnoreCase("ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (filenameExtension.equalsIgnoreCase("docx") || filenameExtension.equalsIgnoreCase("doc")) {
            return "application/msword";
        }
        if (filenameExtension.equalsIgnoreCase("xml")) {
            return "text/xml";
        }
        return "image/jpeg";
    }

    /**
     * 获得url链接
     *
     * @param key
     * @return
     */
    public String getUrl(String key) {
        // 设置URL过期时间为10年 3600l* 1000*24*365*10
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
        // 生成URL
        URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
        /*        url = "https://" + bucketName + ".oss-cn-beijing.aliyuncs.com/" + bucketName+"/"+ key;*/
        if (url != null) {

            String host = "https://" + url.getHost() + url.getPath();

            return host;
        }

        return "";
    }

    //
    public InputStream bufferedImageToInputStream(BufferedImage image) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            BufferedImage tag;
            tag = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB_PRE);
            Graphics g = tag.getGraphics();
            g.drawImage(image, 0, 0, null); // 绘制缩小后的图
            g.dispose();
            ImageIO.write(image, "jpg", os);
            InputStream input = new ByteArrayInputStream(os.toByteArray());
            return input;
        } catch (IOException e) {
            log.error("提示:", e);
        }
        return null;
    }

    //
    public InputStream bufferedImagePNRToInputStream(BufferedImage image) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            BufferedImage tag;
            tag = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB_PRE);
            Graphics g = tag.getGraphics();
            g.drawImage(image, 0, 0, null); // 绘制缩小后的图
            g.dispose();
            image = tag;
            ImageIO.write(image, "png", os);
            InputStream input = new ByteArrayInputStream(os.toByteArray());
            return input;
        } catch (IOException e) {
            log.error("提示:", e);
        }
        return null;
    }

    public static BufferedImage toBufferedImage(MultipartFile file) {
        BufferedImage srcImage = null;
        try {
            FileInputStream in = (FileInputStream) file.getInputStream();
            srcImage = javax.imageio.ImageIO.read(in);
        } catch (IOException e) {

        }
        return srcImage;
    }

    /**
     * 删除单个文件
     *
     * @param objectName
     * @return
     */
    public int deleteObject(String objectName) throws IOException {
        // 创建OSSClient实例。
        int result = 1;
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            // 删除文件。如需删除文件夹，请将ObjectName设置为对应的文件夹名称。如果文件夹非空，则需要将文件夹下的所有object删除后才能删除该文件夹。
            ossClient.deleteObject(bucketName, "/SAAS/1616573466363.jpg");
            System.out.println("1111");
        } catch (Exception e) {
            e.printStackTrace();
            result = 0;
        }
        // 关闭OSSClient。
        ossClient.shutdown();
        return result;
    }

    /**
     * 删除多个文件
     *
     * @param keys
     * @return
     */
    public List<String> deleteObjects(List<String> keys) throws IOException {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        List<String> deletedObjects = null;
        try {
            DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(keys));
            deletedObjects = deleteObjectsResult.getDeletedObjects();
        } catch (Exception e) {
        }
        // 关闭OSSClient。
        ossClient.shutdown();
        return deletedObjects;
    }

    /**
     * 下载OSS资源
     *
     * @param objectName
     * @return
     */
    public void downVideo(String fileName, String objectName, HttpServletResponse response) throws IOException {
        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            // 调用ossClient.getObject返回一个OSSObject实例，该实例包含文件内容及文件元信息。
            OSSObject ossObject = ossClient.getObject(bucketName, objectName);

            // 已缓冲的方式从字符输入流中读取文本，缓冲各个字符，从而提供字符、数组和行的高效读取
            //BufferedReader reader = new BufferedReader(new  InputStreamReader(ossObject .getObjectContent()));
            BufferedInputStream in = new BufferedInputStream(ossObject.getObjectContent());
            // 缓冲文件输出流
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            // 通知浏览器以附件形式下载
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            byte[] car = new byte[1024];
            int L = 0;
            while ((L = in.read(car)) != -1) {
                out.write(car, 0, L);
            }
            if (out != null) {
                out.flush();
                // 数据读取完成后，获取的流必须关闭，否则会造成连接泄漏，导致请求无连接可用，程序无法正常工作。
                out.close();
            }
            if (in != null) {
                in.close();
            }
            // 关闭OSSClient。
            ossClient.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
